package com.golxen.utils;

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.util.Properties;

public class YmlUtil {
    private static Properties initYmlObject;
    private static Properties ymlObject=new Properties();

//    private static Map<String,String> valueMap= new HashMap<>();
    //获取application.yml文件中的属性配置
    static {
        Resource resource = new ClassPathResource("application.yml");
        Properties properties = null;
        try {
            YamlPropertiesFactoryBean yamlFactory = new YamlPropertiesFactoryBean();
            yamlFactory.setResources(resource);
            properties =  yamlFactory.getObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        assert properties != null;
        initYmlObject= properties;
    }

    public static void init(){
        Properties configYmlObject=getProperties(getInitString());
        ymlObject.putAll(configYmlObject);
        Properties dbYmlObject=getProperties(getString("db.path"));
        ymlObject.putAll(dbYmlObject);
        Properties redisYmlObject=getProperties(getString("redis.path"));
        ymlObject.putAll(redisYmlObject);
        Properties nettyYmlObject=getProperties(getString("netty.path"));
        ymlObject.putAll(nettyYmlObject);
    }


    private static String getInitString(){
         try {
             return (String) initYmlObject.get("config.path");
         }catch (ClassCastException e){
             return String.valueOf(initYmlObject.get("config.path"));
         }

    }

    private static Properties getProperties(String path){
        Resource resource = new ClassPathResource(path);
        Properties properties = null;
        try {
            YamlPropertiesFactoryBean yamlFactory = new YamlPropertiesFactoryBean();
            yamlFactory.setResources(resource);
            properties =  yamlFactory.getObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        assert properties != null;
        return properties;
    }

    public static String getString(String key){
        try {
            return (String) ymlObject.get(key);
        }catch (ClassCastException e){
            return String.valueOf(ymlObject.get(key));
        }
    }

    public static int getInt(String key){
        return (Integer) ymlObject.get(key);
    }
    public static long getLong(String key){
        return Long.parseLong(String.valueOf(ymlObject.get(key))) ;
    }
    public static boolean getBoolean(String key){
        return (Integer) ymlObject.get(key) != 0;
    }

}
